# coding: utf-8
from django import http
from collections import OrderedDict
from .models import GoodsCategory, GoodsChannel, SKU, SKUImage, SKUSpecification, \
    GoodsSpecification, SpecificationOption


def get_breadcrumb(category):
    dict = {
        'cat1': '',
        'cat2': '',
        'cat3': ''
    }
    if category.parent is None:
        dict['cat1'] = category.name
    elif category.parent.parent is None:
        dict['cat2'] = category.name
        dict['cat1'] = category.parent.name
    else:
        dict['cat3'] = category.name
        dict['cat2'] = category.parent.name
        dict['cat1'] = category.parent.parent.name
    return dict


def get_goods_and_spec(sku_id):

    # ======== 获取该商品和该商品对应的规格选项id ========
    # 根据 sku_id 获取该商品(sku)
    sku = SKU.objects.get(id=sku_id)
    # 获取该商品的图片
    sku.images = SKUImage.objects.filter(sku=sku)

    # ======== 获取类别下所有商品对应的规格选项id ========
    # 根据sku对象,获取对应的类别
    goods = sku.goods

    # 获取该类别下面的所有商品
    skus = SKU.objects.filter(goods=goods)

    dict = {}
    for temp_sku in skus:
        # 获取每一个商品(temp_sku)的规格参数
        sku_zuhe = SKUSpecification.objects.filter(sku=temp_sku).order_by('spec_id')

        temp_list = []
        for zuhe in sku_zuhe:
            # 规格 ---> 规格选项 ---> 规格选项id ----> 保存到[]
            temp_list.append(zuhe.option.id)

        # 把 list 转为 () 拼接成 k : v 保存到dict中:
        dict[tuple(temp_list)] = temp_sku.id

    # ======== 在每个选项上绑定对应的sku_id值 ========
    guige_list = GoodsSpecification.objects.filter(goods=goods).order_by('id')

    for index, guige in enumerate(guige_list):
        # 该规格的选项
        guige_xuanxiang = SpecificationOption.objects.filter(spec=guige)
        for xuanxiang in guige_xuanxiang:
            # 在规格参数sku字典中查找符合当前规格的sku
            temp_list[index] = xuanxiang.id
            xuanxiang.sku_id = dict.get(tuple(temp_list))

        guige.spec_options = guige_xuanxiang

    return goods, guige_list, sku

def get_categories():
    dict = OrderedDict()
    channels = GoodsChannel.objects.order_by('group_id','sequence')
    for channel in channels:
        group_id = channel.group_id
        if group_id not in dict:
            dict[group_id] = {
                'channels':[],
                'sub_cats':[]
            }
        cat1 = channel.category
        dict[group_id]['channels'].append({
            'id':cat1.id,
            'name':cat1.name,
            'url':channel.url
        })
        cat2s = GoodsCategory.objects.filter(parent=cat1)
        for cat2 in cat2s:
            cat2.sub_cats = []
            cat3s = GoodsCategory.objects.filter(parent=cat2)
            for cat3 in cat3s:
                cat2.sub_cats.append(cat3)
            dict[group_id]['sub_cats'].append(cat2)
        return dict